import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
from lightgbm import log_evaluation, early_stopping
# 假设我们有一个CSV文件 'sales_data.csv' 包含 date, sku, sale_qty 列
data = pd.read_csv('Test.csv', low_memory=False, encoding='GBK')

# 数据预处理：将日期转换为时间戳特征
data['date_id'] = pd.to_datetime(data['date_id'], format='%Y%m%d')
data['day_of_week'] = data['date_id'].dt.dayofweek
data['month'] = data['date_id'].dt.month
data['year'] = data['date_id'].dt.year
data.drop(columns=['date_id'], inplace=True)

# 特征列和目标列
features = ['sku', 'day_of_week', 'month', 'year']
target = 'sales_qty'

X = data[features]
y = data[target]

# 将字符串类型的 SKU 转换为数值类型
X['sku'] = X['sku'].astype('category').cat.codes

# 分割数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建 LightGBM 数据集
train_data = lgb.Dataset(X_train, label=y_train)
test_data = lgb.Dataset(X_test, label=y_test, reference=train_data)

# 设置 LightGBM 参数
params = {
    'objective': 'regression',
    'metric': 'rmse',
    'boosting_type': 'gbdt',
    'num_leaves': 31,
    'learning_rate': 0.05,
    'feature_fraction': 0.9
}

callbacks = [log_evaluation(period=100), early_stopping(stopping_rounds=30)]

# 训练模型
model = lgb.train(params, train_data, num_boost_round=100, valid_sets=[test_data], callbacks= callbacks)

# 进行预测
y_pred = model.predict(X_test, num_iteration=model.best_iteration)

# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print(f'Mean Squared Error: {mse}')

# 显示前几条真实值和预测值的对比
comparison_df = pd.DataFrame({'Actual': y_test.values, 'Predicted': y_pred})
print(comparison_df.head())



